export class CssMaskEffect {
  constructor() {
    this.skeletonDom = this.getSkeleton()
    this.animation = this.createAnimation()
    this.init()
  }
  get html() {
    return this.skeletonDom
  }
  destroy() {
    this.skeletonDom.remove()
  }
  init() {
    this.registerProperty()
  }
  appendHtml(html) {
    if (typeof html === 'string') {
      this.skeletonDom.firstElementChild.innerHTML = html
    } else {
      this.skeletonDom.firstElementChild.appendChild(html)
    }
    return this
  }
  show() {
    const { offsetHeight, offsetWidth } = this.skeletonDom
    requestAnimationFrame(() => {
      this.skeletonDom.style.visibility = 'visible'
      this.skeletonDom.style.maskImage = `linear-gradient(atan(${offsetHeight} / ${offsetWidth}), #000 0%, #000 var(--pct-mask), transparent var(--pct-mask), transparent 100%)`
      this.animation.play()
    })
  }

  registerProperty() {
    if ('registerProperty' in CSS) {
      try {
        CSS.registerProperty({
          name: '--pct-mask', // 自定义属性名
          syntax: '<percentage>', // 定义值的类型
          inherits: false, // 是否可继承
          initialValue: '0%', // 初始值
        })
      } catch (err) {
        console.log('🚀 ~ CssMaskEffect ~ registerProperty ~ err:', err)
      }
    }
  }

  createAnimation() {
    return new Animation(
      new KeyframeEffect(
        this.skeletonDom,
        [
          {
            '--pct-mask': '0%',
          },
          {
            '--pct-mask': '100%',
          },
        ],
        {
          duration: 500,
          fill: 'both',
        },
      ),
    )
  }

  getSkeleton() {
    const htmlString = `
    <div>
        <div slot-1></div>
        <svg class>
            <line x1="0" y1="100%" x2="100%" y2="0" stroke="rgba( 255, 255, 255, 0.90 )" stroke-width="1"  />
        </svg>
    </div>
                `
    const rootCss = `
            display: grid;
            grid-template-columns: repeat(2, auto);
            grid-template-rows: repeat(2, auto);
            width: max-content;
            visibility: hidden;
                `
    const css1 = `
                grid-row: 1 / 2;
                grid-column: 2 / 3;
                `
    const css2 = `
                grid-row: 2/3;
                grid-column: 1/2;
                width: 50px;
                height: 50px;
                transform: translate(1px, -1px);
                `

    const parser = new DOMParser()
    const doc = parser.parseFromString(htmlString, 'text/html')
    const root = doc.body.firstChild
    root.style.cssText = rootCss
    root.firstElementChild.style.cssText = css1
    root.lastElementChild.style.cssText = css2
    return root
  }
}
